package com.umer.pinban.staff;

import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.common.CommonApplication;
import com.common.base.activity.BaseActivity;
import com.common.bean.InfoResult;
import com.common.bean.MsgBean;
import com.common.bean.UserInfo;
import com.common.okhttp.OkEntityListRequest;
import com.common.ui.barlibrary.ImmersionBar;
import com.common.ui.loadsir.callback.EmptyCallback;
import com.common.ui.loadsir.callback.ErrorCallback;
import com.common.ui.loadsir.callback.NoNetCallback;
import com.common.ui.recycleview.listener.DataStateListener;
import com.common.ui.recycleview.listener.OptListener;
import com.common.utils.Constants;
import com.common.utils.EventConstants;
import com.umer.pinban.AppHolder;
import com.umer.pinban.R;
import com.umer.pinban.adapter.staff.SelectStaffAdapter;
import com.umer.pinban.bean.customer.CustomerBean;
import com.umer.pinban.bean.staff.StaffBean;
import com.umer.pinban.utils.PinYinUtil;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;

public class SelectStaffActivity extends BaseActivity implements OptListener,DataStateListener {

    @BindView(R.id.linear_back)
    LinearLayout linearBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.linear_submit)
    LinearLayout linearSubmit;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.linear_search)
    LinearLayout linearSearch;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    private List<StaffBean> staffBeans = new ArrayList<>();
    private SelectStaffAdapter selectStaffAdapter;
    private UserInfo userInfo;
    private StaffBean staffBean = null;
    private Handler handler = new Handler();
    private String keywords = "";
    private String staffName = "";
    private int staffId = -1;
    /**
     * 请求数据
     */
    private Runnable delayGetData = new Runnable() {
        @Override
        public void run() {
            loadData();
        }
    };
    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable delayRun = new Runnable() {
        @Override
        public void run() {
            selectStaffAdapter.setDataSource(searchCustomer(keywords));
        }
    };

    @Override
    public boolean isImmersionBarEnabled() {
        return true;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                //是否可以修改导航栏颜色，默认为true
                .navigationBarEnable(true)
                //导航栏颜色，不写默认黑色
                .navigationBarColor(R.color.barcolor)
                .statusBarColor(R.color.colorPrimary)
                //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                .fitsSystemWindows(true)
                .init();
    }

    @Override
    public boolean isSupportSwipeBackEnabled() {
        return false;
    }

    @Override
    public View isSupportLoadSirEnabled() {
        return llContent;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_select_staff;
    }

    @Override
    public void init() {
        staffId = super.getIntent().getIntExtra("staffId",staffId);
        userInfo = AppHolder.getInstance().getUserInfo();
        selectStaffAdapter = new SelectStaffAdapter(this, staffBeans,
                R.layout.activity_select_staff_item, this,this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(selectStaffAdapter);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(TextUtils.isEmpty(s.toString())){
                    if (delayGetData != null) {
                        handler.postDelayed(delayGetData, 300);
                    }
                }else{
                    if (delayRun != null) {
                        //每次editText有变化的时候，则移除上次发出的延迟线程
                        handler.removeCallbacks(delayRun);
                        //延迟800ms，如果不再输入字符，则执行该线程的run方法
                        keywords = etSearch.getText().toString();
                        handler.postDelayed(delayRun, 800);
                    }
                }
            }
        });
    }

    @Override
    public void loadData() {
        selectStaffList();
    }

    private void selectStaffList() {
        OkEntityListRequest<StaffBean> request = new OkEntityListRequest<>(R.id.personnelList,
                Constants.personnelList, StaffBean.class);
        request.addParams("shopId", userInfo.getShopId());
        request.setHeader(true);
        requestOkhttpEntityList(request);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            MsgBean msgBean = new MsgBean();
            msgBean.setFlag(EventConstants.select_staff);
            msgBean.setObject(staffBean);
            getEventBus().post(msgBean);
            CommonApplication.getInstance().finishActivity(this);
            //overridePendingTransition(R.anim.anim_in, R.anim.anim_out);
            return true;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @OnClick({R.id.linear_back,R.id.linear_submit})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.linear_back:
                MsgBean msgBean1 = new MsgBean();
                msgBean1.setFlag(EventConstants.select_staff);
                msgBean1.setObject(staffBean);
                getEventBus().post(msgBean1);
                finish();
                break;
            case R.id.linear_submit:
                if (staffBean == null) {
                    showToast("请选择顾客");
                } else {
                    MsgBean msgBean2 = new MsgBean();
                    msgBean2.setFlag(EventConstants.select_staff);
                    msgBean2.setObject(staffBean);
                    getEventBus().post(msgBean2);
                    finish();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onOptClick(View view, Object object) {
        int index = (int) object;
        switch (view.getId()) {
            case R.id.linear_select:
                boolean select = selectStaffAdapter.getDataSource().get(index).isSelect();
                if (select) {
                    selectStaffAdapter.getDataSource().get(index).setSelect(false);
                    staffBean = null;
                } else {
                    selectStaffAdapter.getDataSource().get(index).setSelect(true);
                    staffBean = selectStaffAdapter.getDataSource().get(index);
                    for (int i = 0; i < selectStaffAdapter.getDataSource().size(); i++) {
                        if (i != index) {
                            selectStaffAdapter.getDataSource().get(i).setSelect(false);
                        }
                    }
                }
                selectStaffAdapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }

    @Override
    public void onDataState(int flag) {
        //1:没有网络 2:没有数据 3:获取数据失败 4:显示内容
        switch (flag) {
            case 1:
                if(loadService!=null){
                    loadService.showCallback(NoNetCallback.class);
                }
                break;
            case 2:
                if(loadService!=null){
                    loadService.showCallback(EmptyCallback.class);
                }
                break;
            case 3:
                if(loadService!=null){
                    loadService.showCallback(ErrorCallback.class);
                }
                break;
            case 4:
                if(loadService!=null){
                    loadService.showSuccess();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onSuccess(int what, InfoResult t) {
        switch (what) {
            case R.id.personnelList:
                staffBeans = (List<StaffBean>) t.getT();
                if(staffBeans!=null && staffBeans.size()>0){
                    for(int i=0;i<staffBeans.size();i++){
                        if(staffBeans.get(i).getPersonnelId()==staffId){
                            staffBeans.get(i).setSelect(true);
                            staffBean = staffBeans.get(i);
                        }
                        String name = staffBeans.get(i).getName();
                        String nameEnglish = PinYinUtil.getFirstSpell(name);
                        staffBeans.get(i).setNameEnglish(nameEnglish);
                    }
                }
                selectStaffAdapter.setDataSource2(staffBeans, t);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onFail(int what, InfoResult t) {
        switch (what) {
            case R.id.personnelList:
                staffBeans = (List<StaffBean>) t.getT();
                if(staffBeans!=null && staffBeans.size()>0){
                    for(int i=0;i<staffBeans.size();i++){
                        String name = staffBeans.get(i).getName();
                        String nameEnglish = PinYinUtil.getFirstSpell(name);
                        staffBeans.get(i).setNameEnglish(nameEnglish);
                    }
                }
                selectStaffAdapter.setDataSource2(staffBeans, t);
                break;
            default:
                break;
        }
    }

    // 判断一个字符是否是中文
    private boolean isChinese(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;// 根据字节码判断
    }

    private List<StaffBean> searchCustomer(String keyword){
        List<StaffBean> infos = new ArrayList<>();
        if(!TextUtils.isEmpty(keyword)){
            String temp = keyword;
            //提取字符串中所有的英文
            String epart = keyword.trim().replaceAll("[^a-z^A-Z]", "").toLowerCase();
            //提取字符串中所有的中文
            String cpart = keyword.trim().replaceAll("[^\\u4e00-\\u9fa5]", "");
            if(staffBeans!=null && staffBeans.size()>0){
                for(int i=0;i<staffBeans.size();i++){
                    String nameChinese = staffBeans.get(i).getName();
                    String nameEnglish = staffBeans.get(i).getNameEnglish().toLowerCase();
                    //中文判断
                    if(cpart!=null && !cpart.equals("") && !cpart.equals("null")){
                        if(nameChinese!=null && !nameChinese.equals("") && !nameChinese.equals("null")){
                            if(nameChinese.contains(cpart)){
                                infos.add(staffBeans.get(i));
                                continue;
                            }
                        }
                    }
                    if(epart!=null && !epart.equals("") && !epart.equals("null")){
                        if(nameEnglish!=null && !nameEnglish.equals("") && !nameEnglish.equals("null")){
                            int length = epart.length();
                            if(length==1){
                                if(nameEnglish.substring(0,1).equals(epart)){
                                    infos.add(staffBeans.get(i));
                                    continue;
                                }
                            }else if(length==2){
                                if(nameEnglish.length()>=2){
                                    if(nameEnglish.substring(0,2).equals(epart)){
                                        infos.add(staffBeans.get(i));
                                        continue;
                                    }
                                }
                            }else if(length==3){
                                if(nameEnglish.length()>=3){
                                    if(nameEnglish.substring(0,3).equals(epart)){
                                        infos.add(staffBeans.get(i));
                                        continue;
                                    }
                                }
                            }else if(length==4){
                                if(nameEnglish.length()>=4){
                                    if(nameEnglish.substring(0,4).equals(epart)){
                                        infos.add(staffBeans.get(i));
                                        continue;
                                    }
                                }
                            }else {
                                continue;
                            }
                        }
                    }
                }
                return infos;
            }else {
                return infos;
            }
        }else {
            return infos;
        }
    }
}
